package com.dreamlin.gankio.mvvm.home.other

import android.view.View
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.api.load
import com.dreamlin.gankio.R
import com.dreamlin.gankio.base.ui.*
import com.dreamlin.gankio.common.getScreenHeight
import com.dreamlin.gankio.common.isFastDoubleClick
import com.dreamlin.gankio.common.jump
import com.dreamlin.gankio.mvvm.home.GankEntity
import com.dreamlin.gankio.mvvm.home.feature.itemViewPool
import com.dreamlin.gankio.mvvm.home.feature.pageSize
import com.dreamlin.gankio.webview.WebActivity
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

/**
 * <p> Title: FeatureFragment </p>
 * <p> Description: </p>
 * @author:  dreamlin
 * @date:    9/20/20
 * @version: V1.0.0
 * Created by dreamlin on 9/20/20.
 */


class OtherFragment : BaseFragment<OtherViewModel>(), AdapterListener<GankEntity>,
    ItemClickListener<GankEntity> {
    override val layout: Int
        get() = R.layout.fragment_ganhuo
    private lateinit var adapter: DiffBaseAdapter<GankEntity>
    private var entities = arrayListOf<GankEntity>()
    private lateinit var tab: String
    var maxPage: Int = 1
    var page: Int = 1
    val refreshDelay = 500

    override fun initViews() {
        rvItems.setHasFixedSize(true)
        rvItems.layoutManager = LinearLayoutManager(activity)
        if (itemViewPool == null) {
            itemViewPool = rvItems.recycledViewPool
        } else {
            rvItems.setRecycledViewPool(itemViewPool)
        }
        adapter = DiffBaseAdapter(entities, R.layout.item_gankhuo)
        adapter.setListener(this)
        adapter.setItemClickListener(this)
        rvItems.adapter = adapter
        rvItems.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var scrollY = 0
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                scrollY += dy
                recyclerView.computeVerticalScrollOffset()
                if (!floating.isShown) {
                    if (scrollY >= getScreenHeight())
                        floating.show()

                } else {
                    if (scrollY < getScreenHeight())
                        floating.hide()
                }
            }
        })
        refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (page >= maxPage) {
                    toast(R.string.no_more_data)
                    refreshLayout.finishLoadMore(refreshDelay)
                    return
                }
                viewModel.loadMoreData(tab, ++page, pageSize)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                viewModel.refreshData(adapter, entities, tab)
            }
        })
        floating.setOnClickListener {
            if (isFastDoubleClick(it.id)) return@setOnClickListener
            rvItems.smoothScrollToPosition(0)
        }
    }

    override fun initData() {
        super.initData()
        tab = arguments?.getString("TAB", "") ?: ""
        viewModel.gankEntities.observe(this, Observer {
            maxPage = it.page_count
            if (it.data.isNotEmpty()) {
                when (refreshLayout.state) {
                    RefreshState.Refreshing -> {
                        entities.clear()
                        entities.addAll(it.data)
                        refreshLayout.finishRefresh()
                    }
                    RefreshState.Loading -> {
                        val start = entities.size
                        entities.addAll(it.data)
                        adapter.notifyItemRangeInserted(start, it.data.size)
                        refreshLayout.finishLoadMore()
                    }
                    RefreshState.None -> {
                        entities.addAll(it.data)
                        adapter.notifyDataSetChanged()
                    }
                }
            } else {
                if (refreshLayout.state == RefreshState.Refreshing) {
                    refreshLayout.finishRefresh()
                } else if (refreshLayout.state == RefreshState.Loading) {
                    refreshLayout.finishLoadMore()
                }
            }
        })
        viewModel.loadMoreData(tab, 1, pageSize)
    }

    override fun convert(holder: BaseViewHolder<GankEntity>, bean: GankEntity) {
        val iv = holder.getView<ImageView>(R.id.image)
        val ivCategory = holder.getView<ImageView>(R.id.ivCategory)
        if (bean.images.isNotEmpty()) {
            iv.load(bean.images[0])
        }
        holder.setText(R.id.tvTag, bean.type)
        holder.setText(R.id.tvHeading, bean.title)
        holder.setText(R.id.tvDescription, bean.desc)
        holder.setText(R.id.tvAuthor, bean.author)
        val split = bean.createdAt.split(' ')
        if (split.isNotEmpty()) {
            holder.setText(R.id.tvDate, split[0])
        }
    }

    override fun onItemClick(view: View, bean: GankEntity) {
        if (!isFastDoubleClick(view.id)) {
            jump(requireContext(), WebActivity::class.java, bean.title, 0, bean.url)
        }
    }

    override fun click(v: View) {

    }

    override fun getVM(): Class<OtherViewModel> {
        return OtherViewModel::class.java
    }

}